package top.bluesword.laboratory.org.hibernate.dialect;

import io.hypersistence.utils.hibernate.type.json.JsonBinaryType;
import org.hibernate.QueryException;
import org.hibernate.dialect.function.SQLFunction;
import org.hibernate.engine.spi.Mapping;
import org.hibernate.engine.spi.SessionFactoryImplementor;
import org.hibernate.type.Type;

import java.util.List;

/**
 * @author 李林峰
 */
public class PostgreSQLCastToJsonbFunctions implements SQLFunction {
    @SuppressWarnings("unused") // Used by Hibernate
    public static String castToJsonB(String input) {
        return "CAST(" + input + " AS jsonb)";
    }

    @Override
    public boolean hasArguments() {
        return true;
    }

    @Override
    public boolean hasParenthesesIfNoArguments() {
        return true;
    }

    @Override
    public Type getReturnType(Type firstArgumentType, Mapping mapping) throws QueryException {
        return JsonBinaryType.INSTANCE;
    }

    @Override
    public String render(Type firstArgumentType, List arguments, SessionFactoryImplementor factory) throws QueryException {
        return String.format("cast(%s as jsonb)",arguments.get(0));
    }

}